{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Examples require an initialized GsSession and relevant entitlements. External clients need to substitute thier own client id and client secret below. Please refer to [Authentication](https://developer.gs.com/p/docs/institutional/platform/authentication/) for details."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from gs_quant.session import GsSession\n",
    "\n",
    "GsSession.use(client_id=None, client_secret=None, scopes=('read_product_data',))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## How to query data \n",
    "The Data APIs support many ways to query datasets to intuitively fetch only the data users need.\n",
    "More details on [Querying Data](https://developer.gs.com/p/docs/services/data/data-access/query-data/) can be found in the documentation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import date, timedelta, datetime\n",
    "from gs_quant.data import Dataset\n",
    "import pydash"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Data in Marquee is available in the form of Datasets (collections of homogenous data). Each Dataset has a set of entitlements, a fixed schema, and assets in coverage."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset_id = 'FXIVOL_STANDARD'  # https://marquee.gs.com/s/developer/datasets/FXIVOL_STANDARD\n",
    "ds = Dataset(dataset_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "Data for limited number of assets or spanning a small time frame can be queried in one go by specifying the assets to query and date/time range."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "start_date = date(2024, 1, 15)\n",
    "end_date = date(2024, 1, 18)\n",
    "\n",
    "data = ds.get_data(start_date, end_date, bbid=[\"EURUSD\"])\n",
    "data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Instead of a range, one can also specify a set of date/times to get data for just those specific date/times"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = ds.get_data(dates=[date(2025, 1, 15), date(2025, 1, 18)], bbid=['EURCAD'])\n",
    "data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For larger number of assets or for longer time ranges, \n",
    "we recommend iterating over assets and time to avoid hitting API query limits. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# loop over assets\n",
    "def iterate_over_assets(\n",
    "    dataset, coverage, start, end, batch_size=5, query_dimension='assetId', delta=timedelta(days=6)\n",
    "):\n",
    "    for ids in pydash.chunk(coverage[query_dimension].tolist(), size=batch_size):\n",
    "        print('iterate over assets', ids)\n",
    "        iterate_over_time(start, end, ids, dataset, delta=delta, query_dimension=query_dimension)\n",
    "\n",
    "\n",
    "# loop over time\n",
    "def iterate_over_time(start, end, ids, dataset, delta=timedelta(days=6), query_dimension='assetId'):\n",
    "    iter_start = start\n",
    "    while iter_start < end:\n",
    "        iter_end = min(iter_start + delta, end)\n",
    "        print('time iteration since', iter_start, 'until', iter_end)\n",
    "        data = dataset.get_data(iter_start, iter_end, **{query_dimension: ids})\n",
    "        # Add your code here to make use of fetched data\n",
    "\n",
    "        iter_start = iter_end"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "dataset_id = 'EDRVOL_PERCENT_V1_STANDARD'  # https://marquee.gs.com/s/developer/datasets/EDRVOL_PERCENT_V1_STANDARD\n",
    "ds = Dataset(dataset_id)\n",
    "\n",
    "coverage = ds.get_coverage()\n",
    "\n",
    "iterate_over_assets(ds, coverage, date(2025, 3, 1), date(2021, 3, 31), batch_size=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similar approach can be used to download all data of a dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "coverage = ds.get_coverage(include_history=True)\n",
    "coverage = coverage.sort_values(by='historyStartDate', axis=0)\n",
    "start_date = datetime.strptime(coverage['historyStartDate'].values[0], '%Y-%m-%d').date()\n",
    "\n",
    "# warning: long running operation if ran on whole of coverage for all time\n",
    "iterate_over_assets(ds, coverage.head(), date.today() - timedelta(days=90), date.today())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "metadata": {
     "collapsed": false
    },
    "source": []
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
